<template>
  <div>
    <bread-crumb
      class="bread-crumb-padding"
      :list="breadCrumb"
      :user="true"
    ></bread-crumb>
    <div class="user-main-box">
      <accountTabList
        :list="tablist"
        :cidList="cidList"
        :cidSelect="cidSelect"
        @cidSelectChange="cidSelectChange"
      ></accountTabList>
      <div class="filter-line b-b-d flx-row-s-c">
        <span class="item-name">交易类型</span>
        <span
          v-for="(item, index) in dealType"
          :key="'r' + index"
          class="select-item"
          :class="[item.value === dealTypeSelect ? 'active' : 'normal']"
          style="margin-right: 40px"
          @click="dealTypeSelectChange(item.value)"
        >
          {{ item.name }}
        </span>
      </div>
      <div class="filter-line b-b-d flx-row-s-c">
        <span class="item-name">交易时间</span>
        <Select @on-change="changeDateType" v-model="dateType" style="width: 150px; margin-right: 10px">
          <Option
              v-for="item in dateTypeList"
              :value="item.type"
              :key="item.type"
          >{{ item.name }}</Option
          >
        </Select>
        <DatePicker
          :editable="false"
          ref="datePicker"
          type="daterange"
          split-panels
          placeholder="请选择"
          style="width: 210px"
          @on-change="dateChange"
          :options="dateOption"
          :value="time"
        ></DatePicker>
        <span class="item-name">财务类型</span>
        <Select v-if="dealTypeSelect === -1" v-model="financialTypeSelect" style="width: 150px">
          <OptionGroup v-for="group in financialTypeList" :label="group.label" :key="group.label" >
            <Option
                v-for="item in group.options"
                :value="item.type"
                :key="item.type"
            >{{ item.name }}</Option
            >
          </OptionGroup>
        </Select>
        <Select v-else v-model="financialTypeSelect" style="width: 150px">
          <Option
              v-for="item in financialTypeList"
              :value="item.type"
              :key="item.type"
          >{{ item.name }}</Option
          >
        </Select>
        <span class="item-name" style="text-align: right">域名</span>
        <div class="wrapdmTextarea">
          <div class="textarea-warp" style="z-index: 200; top: 0;">
            <Input class="ui-input dmTextarea" :class="dmName ? 'dmTyping' : ''" @on-focus="dmName = true"
                   @on-blur="dmName = false" v-model.trim="keyword" type="textarea" placeholder="批量请换行分隔">
              <template #suffix>
                <Icon type="ios-search"/>
              </template>
            </Input>
          </div>
        </div>
        <div
            class="user-strong-button line-button-size"
            style="margin: 0px 10px 0px 30px;"
            @click="pageChange(1)"
        >
          搜索
        </div>
        <div class="user-normal-button line-button-size" @click="reset">
          重置
        </div>
      </div>
    </div>

    <div class="user-main-box pub-m-t-20">
      <div style="position: relative">
        <Spin :withIcon="true" v-if="loading"></Spin>
        <div class="filter-line search-result-line flx-row-s-c">
          <span class="c-black f-14"
            >搜索结果共<span class="c-black">{{
              total != null ? ` ${total} ` : ""
            }}</span
            >条</span
          >

          <div
            class="user-strong-button line-button-size pub-m-l-30"
            @click="exportData"
          >
            导出Excel
          </div>
        </div>
        <div class="my-domain-table">
          <Table
            :loading="loading"
            ref="pushDomianTable"
            :columns="columns"
            :data="list"
            :disabled-hover="true"
            @on-select="onSelectEvent"
            @on-select-cancel="onSelectCancelEvent"
            @on-select-all="onSelectAllEvent"
            @on-select-all-cancel="onSelectAllCancelEvent"
            stripe
          ></Table>
          <div class="form-page-bottom-area flx-row-c-c">
            <Page
              :total="total"
              :current="page"
              :page-size="pageSize"
              :page-size-opts="pageSizeOpts"
              @on-change="pageChange"
              @on-page-size-change="pageSizeChange"
              show-elevator
              show-sizer
              show-total
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { pullAllWith, isEqual } from "lodash";
import { financialType, createDateTypeList } from "@/utils/publicData";
import { getAccountDetail, getCid } from "@/api/user";
import { userExportData } from "@/api/bidding";
import accountTabList from "@/components/tabList/accountTabList";
export default {
  name: "VipCapitaldetails",
  components: {
    accountTabList,
  },

  data() {
    return {
      loading: false,
      dmName: false,
      breadCrumb: [{name: "管理中心"},{ name: "财务管理" }, { name: "资金明细" }],
      tablist: [
        {
          name: "资金明细",
          to: "/user/capitaldetails",
        },
      ],
      dealType: [
        {
          name: "全部",
          value: -1,
        },
        {
          name: "支出",
          value: 0,
        },
        {
          name: "收入",
          value: 1,
        },
        {
          name: "冻结",
          value: 2,
        },
        {
          name: "解冻",
          value: 3,
        },
        {
          name: "返现",
          value: 4,
        },
      ],
      financialTypeList: [],

      // 表单数据
      dealTypeSelect: -1,
      time: [],
      startTime: "",
      endTime: "",
      keyword: "",
      financialTypeSelect: null,

      columns: [
        {
          title: "序号",
          width: 80,
          align: "center",
          render: (h, params) => {
            return h(
              "span",
              params.index + (this.page - 1) * this.pageSize + 1
            );
          },
        },
        {
          title: "交易日期",
          key: "createdTime",
          align: "left",
        },
        {
          width: 60,
          title: "类型",
          key: "amountType",
          align: "left",
          render: (h, params) => {
            let title = this.statusFilter(params.row.amountType);
            return h("span", title);
          },
        },
        {
          title: "财务类型",
          key: "financialType",
          align: "left",
        },
        {
          title: "交易金额",
          key: "amount",
          align: "left",
          render: (h, params) => {
            if (params.row.amountType === 0) {
              return h("span", -params.row.amount);
            } else {
              return h("span", params.row.amount);
            }
          },
        },
        {
          title: "历史余额",
          key: "balance",
          align: "left",
        },
        {
          title: "返现余额",
          key: "rebate",
          align: "left",
        },
        {
          minWidth: 200,
          title: "备注",
          // ellipsis: true,
          key: "remark",
          align: "left",
        },
      ],
      selectAll: false,
      // 保存选中的数据
      selectList: [],

      // 分页设置
      total: null,
      pageSizeOpts: [50, 100, 200],
      pageSize: 50,
      page: 1,
      list: [],
      userId: "",
      cidSelect: "",
      cidList: [
        {
          username: "主账号",
          id: "",
        },
      ],
      dateType: 0,
      dateTypeList: [],
      dateOption: {
      },
    };
  },
  created() {
    this.financialType(-1);
    this.createDateTypeList()
  },
  mounted() {
    const { tab, subTab } = this.$route.query;
    if (tab) {
      this.dealTypeSelect = parseInt(tab);
      this.financialType(this.dealTypeSelect);
    }
    if (subTab) {
      this.financialTypeSelect = parseInt(subTab);
    }
    this.getCidList();
    this.getAccountDetail();
  },
  methods: {
    changeDateType() {
      this.changeDateOption()
    },
    changeDateOption() {
      this.time = []
      this.startTime = null
      this.endTime = null
      this.dateOption = {
        disabledDate: date => {
          let item = this.dateTypeList.filter(item => item.type === this.dateType);
          return date && (date.valueOf() < item[0].startTime || date.valueOf() > item[0].endTime);
        }
      };
    },
    createDateTypeList() {
      this.dateTypeList = createDateTypeList(3)
      this.changeDateOption()
    },
    statusFilter(val) {
      let title = "--";
      switch (val) {
        case 0:
          title = "支出";
          break;
        case 1:
          title = "收入";
          break;
        case 2:
          title = "冻结";
          break;
        case 3:
          title = "解冻";
          break;
        case 4:
          title = "返现";
          break;
      }
      return title;
    },
    // 获取子账号
    async getCidList() {
      const { code, data } = await getCid();
      if (code == 200) {
        this.cidList = this.cidList.concat(data);
      }
    },
    cidSelectChange(row) {
      this.cidSelect = row.index;
      this.userId = row.id;
      this.getAccountDetail();
    },
    // 获取财务类型
    async financialType(type) {
      let list = await financialType();
      if (type === -1) {
        let arr = []
        for (let i = 0; i < 5; i++) {
          let filter = list.filter(
              (item, index, origin) =>
                  index ===
                  origin.findIndex((itemInner) => {
                    return itemInner.type === item.type && i  === item.amountType;
                  })
          );
          if (filter.length > 0) {
            if (i === 0) {
              arr.push({
                label: '支出',
                options: filter
              })
            } else if (i === 1) {
              arr.push({
                label: '收入',
                options: filter
              })
            } else if (i === 2) {
              arr.push({
                label: '冻结',
                options: filter
              })
            } else if (i === 3) {
              arr.push({
                label: '解冻',
                options: filter
              })
            } else if (i === 4) {
              arr.push({
                label: '返现',
                options: filter
              })
            }
          }
        }
        this.financialTypeList = arr;
      } else {
        this.financialTypeList = list.filter(
            (item, index, origin) =>
                index ===
                origin.findIndex((itemInner) => {
                  return itemInner.type === item.type && type === item.amountType;
                })
        );
      }
    },
    // 交易类型改变
    dealTypeSelectChange(value) {
      this.dealTypeSelect = value;
      this.financialType(this.dealTypeSelect)
      this.financialTypeSelect = null
      this.pageChange(1);
    },
    // 日期选择改变
    dateChange(date) {
      this.startTime = date[0];
      this.endTime = date[1];
    },
    // 切换pageSize
    pageSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.pageChange(1);
    },
    // 切换页码
    pageChange(page) {
      this.page = page;
      this.getAccountDetail();
    },
    // 重置
    reset() {
      this.dealTypeSelect = -1;
      this.time = [];
      this.startTime = "";
      this.endTime = "";
      this.keyword = "";
      this.financialTypeSelect = null;
      this.page = 1;
      this.dateType = 0;
      this.getAccountDetail();
    },
    // 获取列表
    async getAccountDetail() {
      this.loading = true;
      let keyword = this.keyword.replace(/\n/g, ",");
      let params = {
        keywords: keyword,
        amountType: this.dealTypeSelect !== -1 ? this.dealTypeSelect : null,
        startTime: this.startTime,
        endTime: this.endTime,
        financialType: this.financialTypeSelect,
        type: this.dateType,
        limit: this.pageSize,
        page: this.page,
      };
      if (this.userId) {
        params.userId = this.userId;
      }
      let res = await getAccountDetail(params);
      if (res.code == 200) {
        this.list = res.data.list;
        this.total = res.data.total;
      }
      this.loading = false;
    },
    // 全选
    handleSelectAll() {
      this.selectAll = !this.selectAll;
      this.$refs.pushDomianTable.selectAll(this.selectAll);
    },
    // checkbox全选的数据
    onSelectAllEvent(selection) {
      this.selectAll = true;
      this.selectList = selection;
    },
    // checkbox取消全选的数据
    onSelectAllCancelEvent() {
      this.selectAll = false;
      this.selectList = [];
    },
    // checkbox单个选中数据
    onSelectEvent(selection, row) {
      this.selectList.push(row);
      if (
        this.selectList.length > 0 &&
        this.selectList.length == this.list.length
      )
        this.selectAll = true;
    },
    // checkbox单个取消数据
    onSelectCancelEvent(selection, row) {
      this.selectList = pullAllWith(this.selectList, [row], isEqual);
      this.selectAll = false;
    },
    // 导出excel
    async exportData() {
      let keyword = this.keyword.replace(/\n/g, ",");
      const params = {
        keywords: keyword,
        amountType: this.dealTypeSelect !== -1 ? this.dealTypeSelect : null,
        startTime: this.startTime,
        endTime: this.endTime,
        financialType: this.financialTypeSelect,
        type: this.dateType,
      };
      if (this.userId) {
        params.userId = this.userId;
      }
      this.loading = true;
      const { code, data } = await userExportData(params);
      this.loading = false;
      if (code === 200 && data) {
        const downloadElement = document.createElement("a");
        const href = window.URL.createObjectURL(data); // 创建下载的链接
        downloadElement.href = href;
        downloadElement.download =
          "资金明细导出信息" + this.$moment().format("yyyy-MM-DD HH-mm"); // 下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); // 点击下载
        document.body.removeChild(downloadElement); // 下载完成移除元素
        window.URL.revokeObjectURL(href); // 释放掉blob对象
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.my-domain-table /deep/ {
  .form-page-bottom-area {
    border: none;
  }
  .ivu-table-wrapper {
    .ivu-table-cell {
      color: #000;
      &:nth-child(1) {
        padding-left: 10px;
        padding-right: 10px;
      }
    }
    .ivu-table-header {
      box-sizing: border-box;
    }
    .ivu-table-row {
      box-sizing: border-box;
      &:hover {
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.15);
        transform: scale(1.01);
      }
    }
  }
  .tab-btn:hover {
    color: $mainColor;
    border-color: $mainColor;
  }
  .tab-btn:focus {
    box-shadow: none;
  }
}
</style>
